package server

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"net"
	"simple_game/app/config"
	"simple_game/app/libs/logger"
	"simple_game/protos/pt"
)

type server struct {
	pt.UnimplementedHelloServer
}

func (s *server) Say(ctx context.Context, req *pt.SayRequest) (*pt.SayResponse, error) {
	fmt.Println("request:", req.Msg)
	return &pt.SayResponse{Msg: "Hello " + req.Msg}, nil
}

func StartGRPC() {
	address := fmt.Sprintf("%s:%s", config.Conf.Rpc.Addr, config.Conf.Rpc.Port)
	listen, err := net.Listen("tcp", address)
	if err != nil {
		fmt.Printf("failed to listen: %v", err)
		return
	}

	s := grpc.NewServer()
	pt.RegisterHelloServer(s, &server{})
	defer func() {
		s.Stop()
		_ = listen.Close()
	}()
	logger.INFO("simple game rpc start suc")
	err = s.Serve(listen)
	if err != nil {
		logger.ERROR("failed to serve", err)
		return
	}

}
